package org.dppc.fine4j.proxychain.support;

import java.lang.reflect.Proxy;

import net.sf.cglib.proxy.Enhancer;

import org.dppc.fine4j.proxychain.ProxyHandler;

/**
 * ProxyHandler 创建工厂
 * 
 * @author maomh
 *
 */
public class ProxyHandlerFactory {
	private ProxyHandlerFactory() {}
	
	/**
	 * 创建一个JDKProxyHandler 
	 * 
	 * @param interfaces
	 * @return
	 */
	public static ProxyHandler newJDKProxyHandler(Class<?>...interfaces) {
		ClassLoader loader =Thread.currentThread().getContextClassLoader();
		JDKProxyHandler handler =new JDKProxyHandler(interfaces);
		Object proxy =Proxy.newProxyInstance(loader, interfaces, handler);
		setProxy(handler, proxy);
		return handler;
	}
	
	
	/**
	 * 创建一个 CGlibProxyHandler
	 * 
	 * @param clazz
	 * @return
	 */
	public static ProxyHandler newCGlibProayHandler(Class<?> clazz) {
		CGlibProxyHandler handler =new CGlibProxyHandler(clazz);
		Object proxy =Enhancer.create(clazz, handler);
		setProxy(handler, proxy);
		return handler;
	}
	
	
	// 为ProxyHandler设置代理对象
	private static void setProxy(AbstractProxyHandler handler, Object proxy) {
		try {
			handler.setProxy(proxy);
		} catch (TypeErrorException e) {
			throw new RuntimeException("设置代理对象类型错误，创建ProxyHandler失败！", e);
		}
	}
}
